/*
 * @Descripttion: [通用混入]
 * @Author: Iseven Monkey <iswoter@gmail.com>
 * @Date: 2023-10-18 10:37:34
 * @LastEditors: Iseven Monkey <iswoter@gmail.com>
 * @LastEditTime: 2024-01-22 12:12:14
 */
export default {
  data() {
    return {};
  },
  computed: {
    /**
     * @description:  是否开发模式,根据运行环境判断
     * @return {Boolean}
     */
    isDev() {
      return process.env.NODE_ENV === "development";
    },

    /**
     * @description:  是否开发模式， 从服务器获取判断
     * @return @return {Boolean}
     */
    isDevMode() {
      const { devMode } = this.$store.getters.settings;
      return devMode === undefined || devMode > 0;
    },

    /**
     * @description:  全局设置，包含语言，主题等，从服务器获取
     * @return {Object}
     */
    settings() {
      return this.$store.getters.settings;
    },

    globalStyle() {
      let style = {};

      const settings = this.$store.getters.settings;

      if (settings && settings.base && settings.base.mappStyle) {
        style = Object.assign(style, settings.base.mappStyle);

        if (style["--background-image"] && style["--background-image"] != "none") {
          style["--background-image"] = "url(" + style["--background-image"] + ")";
        }
        if (style["--font-size"]) {
          style["--font-size"] = this.pxOrRpx(style["--font-size"]);
        }
        if (style["--border"]) {
          style["--border"] = this.pxOrRpx(style["--border"]);
        }

        //--border-radius

        if (style["--border-radius"]) {
          style["--border-radius"] = this.pxOrRpx(style["--border-radius"]);
        }

        //--card-padding

        if (style["--card-padding"]) {
          style["--card-padding"] = this.pxOrRpx(style["--card-padding"]);
        }
      }
      return style;
    },

    /**
     * @description:  token
     * @return {String}
     */
    token() {
      return this.$store.getters.token;
    },

    /**
     * @description:  用户信息
     * @return  {Object}
     */
    user() {
      return this.$store.getters.user;
    },

    /**
     * @description:  用户扩展信息
     * @return  {Object}
     */
    userExtend: {
      get() {
        return this.$store.getters.userExtend;
      },
      set(value) {
        return value;
      },
    },

    /**
     * @description:  用户昵称
     * @return {String}
     */
    nickname() {
      return this.$store.getters.nickname;
    },

    /**
     * @description:  用户头像
     * @return {String}
     */
    avatar() {
      return this.userAvatar(this.$store.getters.avatar);
    },

    /**
     * @description:  用户荣荣耀
     * @return {Object}
     * @example: {name: "青铜", badge: 1}
     *
     */

    userHonour() {
      const credits = this.$store.getters.user.credits;
      const creditCondiction = [
        { name: "青铜", min: 0, max: 500 },
        { name: "白银", min: 501, max: 2000 },
        { name: "黄金", min: 2001, max: 5000 },
        { name: "铂金", min: 5001, max: 10000 },
        { name: "钻石", min: 10001, max: 20000 },
        { name: "星耀", min: 20001, max: 50000 },
        { name: "王者", min: 50001, max: 100000 },
      ];

      let honour = {
        name: creditCondiction[0].name,
        badge: 1,
      };

      const creditCondictionLast = creditCondiction[creditCondiction.length - 1];

      if (credits >= creditCondictionLast.max) {
        honour = {
          name: creditCondictionLast.name,
          badge: creditCondiction.length,
        };
      }
      for (let i = 0; i < creditCondiction.length; i++) {
        if (credits >= creditCondiction[i].min && credits <= creditCondiction[i].max) {
          const item = creditCondiction[i];
          honour = {
            name: item.name,
            badge: i + 1,
          };
          break;
        }
      }
      return honour;
    },

    /**
     * @description:  用户是否已登录
     * @return {Boolean}
     */
    isLogin() {
      return !!this.token;
    },

    /**
     * @description:  小程序右边按钮位置
     * @return {Object}
     */
    menuButtonInfo() {
      let menuButtonInfo = {
        top: 0,
        left: 0,
        width: 0,
        height: 0,
        right: 0,
        bottom: 0,
      };

      // #ifdef MP-WEIXIN
      menuButtonInfo = {
        ...uni.getMenuButtonBoundingClientRect(),
      };
      // #endif

      return menuButtonInfo;
    },

    /**
     * @description:  状态栏高度
     * @return  {Number}
     */
    getStatusBarHeight() {
      //取得状态栏高度
      let statusBarHeight = uni.getSystemInfoSync().statusBarHeight;
      return statusBarHeight + this.menuButtonInfo.top + this.menuButtonInfo.height + 20;
    },

    // 用户头衔
  },
  filters: {},
  mounted() {},
  methods: {
    pxOrRpx(num) {
      //如果是H5
      // #ifdef H5
      const system = uni.getSystemInfoSync();
      //设备宽度 / uni-app规定屏幕基准宽度为750rpx * rpx
      const px = system.windowWidth / 750;
      return num * px + "px";
      // #endif

      //如果不是H5
      // #ifndef H5
      return num + "rpx";
      // #endif
    },
    /**
     * @description:  语言翻译
     * @param {*} key 语言key 例如：auth.login
     * @param {*} lang 语言包
     * @return {*}
     */
    $t(key, lang = null) {
      lang = lang || this.settings.lang || {};

      return key.split(".").reduce((o, i) => {
        if (o) return o[i];
      }, lang);
    },

    /**
     * @description:  图片地址拼接
     * @param {String} value
     * @return {String}
     */
    imgSrc(value) {
      let img = this.$config.images.default;

      if (value) {
        img = value;
        //如果头像不是url或者base64
        if (!img.includes("http") && !img.includes("data:image/")) {
          //如果头像不是以/开头
          if (img[0] !== "/") {
            img = this.$config.apiUrl + "/" + img;
          } else {
            img = this.$config.apiUrl + img;
          }
        }
      }

      return img;
    },

    /**
     * @description:  用户头像地址拼接
     * @param {String} value 例如：/static/images/avatar.png
     * @return {String}
     */
    userAvatar(value) {
      let img = value;
      if (!img) {
        img = this.$config.images.avatar;

        if (!this.token) {
          img = this.$config.images.avatar2;
        }
      }
      return this.imgSrc(img);
    },

    /**
     * @description:  静态资源地址拼接
     * @param {String} value 例如：/static/images/logo.png
     * @return {String}
     */
    staticUrl(value) {
      return this.$config.staticUrl + value;
    },

    /**
     * @description:  检查登陆
     * @param {Boolean} loading 是否显示loading
     * @param {String} redirect 重定向地址
     * @return {*}
     */
    checkAuth(loading = true, redirect = "") {
      if (this.isLogin) {
        return true;
      }
      // 取得当前页面路径
      const pages = getCurrentPages();
      const currentPage = pages[pages.length - 1];
      if (!currentPage || !currentPage.route) {
        return;
      }
      const route = "/" + currentPage.route;

      // 白名单
      const whiteList = this.$config.whiteList;
      if (!whiteList.includes(route)) {
        redirect = redirect || route;
        // 如果不在白名单中，跳转到登录页
        return this.auth(loading, redirect);
      }
    },

    /**
     * @description:  用户鉴权
     * @param {Boolean} loading 是否显示loading
     * @param {String} redirect 重定向地址
     * @return {*}
     */
    auth(loading = true, redirect = "", resData = false) {
      // 如果已经登录，直接返回
      if (this.isLogin) {
        return true;
      }

      // 如果没有重定向地址，取得当前页面路径
      if (!redirect) {
        const pages = getCurrentPages();
        const currentPage = pages[pages.length - 1];
        redirect = "/" + currentPage.route;
      }

      // 如果重定向地址包含auth，清空重定向地址
      if (redirect && redirect.includes("auth")) {
        redirect = "";
      }

      return this.$store.dispatch("auth/auth", {
        loading,
        resData,
        redirect,
      });
    },

    authAsync(loading = true, redirect = "", resData = true) {
      return new Promise((resolve, reject) => {
        // 如果已经登录，直接返回
        if (this.isLogin) {
          return resolve(true);
        }
        this.$store
          .dispatch("auth/auth", {
            loading,
            resData,
            redirect,
          })
          .then((res) => {
            resolve(res);
          })
          .catch((err) => {
            reject(err);
          });
      });
    },

    /**
     * @description:  取得用户信息
     * @return {Promise}
     */
    getUserInfo(
      params = {
        loading: true,
      },
    ) {
      return this.$store.dispatch("auth/getUserInfo", params);
    },

    /**
     * @description:  更新用户扩展信息
     * @return {Promise}
     */
    updateUserExtend() {
      return this.$store.dispatch("auth/updateUserExtend");
    },

    /**
     * @description:  退出登录
     */
    logout() {
      return this.$store.dispatch("auth/logout");
    },

    toLogin() {
      uni.navigateTo({
        url: "/pages/ucenter/login",
        fail(res) {
          console.log(res);
        },
      });
    },

    /**
     * @description:  从元素中提取连接并且跳转
     * @param {*} e 事件对象, e.currentTarget.dataset.to 为跳转地址, 示例 <view @tap="goTo" data-to="/pages/index/index" data-action="switchTab">跳转</view>, data-action 为跳转方式, 默认为 navigateTo, 可选值为 switchTab, reLaunch, redirectTo
     */
    goTo(e) {
      const action = e.currentTarget.dataset.action;
      const url = e.currentTarget.dataset.to;
      console.log(url);
      switch (action) {
        case "switchTab":
          uni.switchTab({
            url,
          });
          break;
        case "reLaunch":
          uni.reLaunch({
            url,
          });
          break;
        case "redirectTo":
          uni.redirectTo({
            url,
          });
          break;
        default:
          uni.navigateTo({
            url,

            fail: (err) => {
              console.log("err", err);
            },
          });
          break;
      }
    },

    goToUrl(url, action = "") {
      switch (action) {
        case "switchTab":
          uni.switchTab({
            url,
          });
          break;
        case "reLaunch":
          uni.reLaunch({
            url,
          });
          break;
        case "redirectTo":
          uni.redirectTo({
            url,
          });
          break;
        default:
          uni.navigateTo({
            url,
            fail: (err) => {
              console.log("goTo", err);
              // switchTab
              uni.switchTab({
                url,
                fail: (err) => {
                  console.log("goTo", err);
                  // reLaunch
                  uni.reLaunch({
                    url,
                    fail: (err) => {
                      console.log("goTo", err);
                      // redirectTo
                      uni.redirectTo({
                        url,
                        fail: (err) => {
                          console.log("goTo", err);

                          // 如果都失败，跳转到首页
                          uni.switchTab({
                            url: "/pages/index/index",
                            fail: (err) => {
                              console.log("goTo", err);
                            },
                          });
                        },
                      });
                    },
                  });
                },
              });
            },
          });
          break;
      }
    },

    // 返回

    /**
     * @description:  返回上一页
     * @return {*}
     * @example: this.goBack()
     * @example: <button @tap="goBack">返回</button>
     * @example: <button @tap="goBack(2)">返回上上页</button>
     */

    goBack(delta = 1) {
      if (getCurrentPages().length > 1) {
        uni.navigateBack(
          {
            delta: getCurrentPages().length,
          },
          200,
        );
      } else {
        this.goToUrl("/pages/index/index");
      }

      //如果是h5 找到class= root-portal的元素删除
      // #ifdef H5
      const rootPortal = document.querySelector(".root-portal");
      if (rootPortal) {
        rootPortal.remove();
      }
      // #endif
    },
    callPhone(phone) {
      uni.makePhoneCall({
        phoneNumber: String(phone),
      });
    },

    //复制文本
    copyText(text) {
      text = String(text);
      uni.setClipboardData({
        data: text,
        success: () => {
          uni.showToast({
            title: "复制成功",
            icon: "success",
          });
        },
      });
    },

    setTitle(title) {
      if (title) {
        uni.setNavigationBarTitle({
          title,
        });
      }
      //如果是H5
      // #ifdef H5
      document.title =
        (title ? title + " - " : "") + (this.settings.base ? this.settings.base.name : "");
      // #endif
    },
  }, //  设置分享

  onShareAppMessage() {
    // 取得当前页面路径
    const pages = getCurrentPages();
    const currentPage = pages[pages.length - 1];
    const path = "/" + currentPage.route;
    const title = this.settings.shareTitle || this.settings.base.name;
    const imageUrl = this.settings.shareImage;
    return {
      title,
      path,
      imageUrl,
    };
  },
};
